package com.talking.view.component;

import com.talking.pojo.SystemVariable;
import com.talking.pojo.User;
import com.talking.view.componentpojo.ColorObj;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.geom.Ellipse2D;

public class HeadImage extends JPanel {
    private int size;
    private String source;
    private int border = 0 ;
    private User mine;
    private Color backGround;

    public HeadImage(int size, String source, MouseAdapter adapter){

        this.mine = SystemVariable.getCurrentUser();
        this.size = size;
        this.source =  "temp/"+mine.getUser_id()+"/"+source+".png";;
        this.border = size/28;
        this.setPreferredSize(new Dimension(size,size));
        this.setSize(size,size);
        this.addMouseListener(adapter);
        this.backGround = ColorObj.MAIN_BACKGROUND;
    }
    public void setBac(Color color){
        this.backGround = color;
    }

    public void paintComponent(Graphics g){
        ImageIcon imageIcon =new ImageIcon(source);
        imageIcon.setImage(imageIcon.getImage().getScaledInstance(size,size,Image.SCALE_DEFAULT));
        Image image =imageIcon.getImage();             //读取文件对象

        Ellipse2D.Double circle = new Ellipse2D.Double(border,border,size-2*border, size-2*border);         //创建一个圆形

        Graphics2D g1 = (Graphics2D) g;
        g1.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);         //抗锯齿

        //填充一个底部圆圈
        g1.setColor(backGround);
        g1.fillOval(0,0,size,size);

        //将图片裁剪成圆形，当时，图片外圈锯齿十分严重
        g1.setClip(circle);
        g1.drawImage(image,border,border,size-2*border, size-2*border,null);

        //为了使图片边缘平滑，没有锯齿，因此需要在图片边缘画一个圆，将锯齿部分覆盖掉
        //stroke是画笔，5f便是画笔的宽度，跨度足够大时，圆会变成圆环，内圆为我们画的圆，圆环为画笔宽度
        Stroke s = new BasicStroke(5F, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
        g1.setStroke(s);
        g1.drawOval(border, border, size - border * 2, size - border * 2);
    }

    public void setImage(String source){
        this.source = "temp/"+mine.getUser_id()+"/"+source+".png";
//        repaint();
    }

    public void setTempImage(String source){
        this.source = source;
//        repaint();

        JComponent parent;
        parent =(JComponent) getParent();

        while(!parent.getUIClassID().equals("PanelUI")){
            parent = (JComponent) parent.getParent();
        }

        parent.updateUI();
    }
}
